package com.fufufu.mail.product.service.impl;

import com.fufufu.common.to.SkuLadderTo;
import com.fufufu.common.to.SkuMemberPriceTo;
import com.fufufu.common.to.SpuBoundTo;
import com.fufufu.common.to.SkureductionTo;
import com.fufufu.mail.product.fegin.MemberPriceFeignService;
import com.fufufu.mail.product.fegin.SkuFullReductionFeignService;
import com.fufufu.mail.product.fegin.SkuLadderFeginService;
import com.fufufu.mail.product.fegin.SpuBoundsFeignService;
import com.fufufu.mail.product.service.*;
import com.fufufu.mail.product.vo.Bounds;
import com.fufufu.mail.product.vo.MemberPrice;
import com.fufufu.mail.product.vo.Skus;
import com.fufufu.mail.product.vo.SpuSaveVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fufufu.common.utils.PageUtils;
import com.fufufu.common.utils.Query;

import com.fufufu.mail.product.dao.SpuInfoDao;
import com.fufufu.mail.product.entity.SpuInfoEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {


    @Resource
    private SpuInfoDescService spuInfoDescService;

    @Resource
    private SpuImagesService spuImagesService;

    @Resource
    private ProductAttrValueService productAttrValueService;

    @Resource
    private SkuInfoService skuInfoService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SpuBoundsFeignService spuBoundsFeignService;

    @Resource
    private SkuFullReductionFeignService skuFullReductionFeignService;

    @Resource
    private SkuLadderFeginService skuLadderFeginService;

    @Resource
    private MemberPriceFeignService memberPriceFeignService;

    /**
     * 保存spuInfo的逻辑
     * @param spuSaveVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 保存pms_spu_info表的信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        Date date = new Date();
        spuInfoEntity.setCreateTime(date);
        spuInfoEntity.setUpdateTime(date);
        this.baseMapper.insert(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();
        Long brandId = spuInfoEntity.getBrandId();
        Long catalogId = spuInfoEntity.getCatalogId();
        // 保存pms_spu_info_desc表的信息
//        List<SpuInfoDescEntity> descEntities = spuSaveVo.getDecript().stream().map((decript) -> {
//            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
//            spuInfoDescEntity.setSpuId(spuId);
//            spuInfoDescEntity.setDecript(decript);
//            return spuInfoDescEntity;
//        }).collect(Collectors.toList());
//        spuInfoDescService.saveBatch(descEntities);
        List<String> decript = spuSaveVo.getDecript();
        // 这里报错了，因为主键不是自增的，而entity里面是自增的，需要去掉
        spuInfoDescService.saveDecript(spuId, decript);
        // 保存pms_spu_images表的信息
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(images, spuId);
        // 保存sms_spu_bounds表的信息
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        spuBoundsFeignService.saveSpuBounds(spuBoundTo);
        // 保存pms_product_attr_value表的信息
        productAttrValueService.saveAttrBySpuId(spuId, spuSaveVo.getBaseAttrs());
        // 以上是SPU的信息
        // 下面是SKU的信息
        List<Skus> skus = spuSaveVo.getSkus();
        // 保存pms_sku_info表的信息，同时获取到id和Skus对应的关系
        Map<Long, Skus> idSkuMapping = skuInfoService.saveSpuInfo(catalogId, brandId, spuId, skus);
        // 保存pms_sku_sale_attr_value表的信息
        skuSaleAttrValueService.savaAttr(idSkuMapping);
        // 保存pms_sku_images表的信息
        skuImagesService.savaImages(idSkuMapping);
        // 保存sms_sku_full_reduction表的信息
        Set<Map.Entry<Long, Skus>> entries = idSkuMapping.entrySet();
        List<SkureductionTo> skureductionTos = new ArrayList<>();
        List<SkuLadderTo> skuLadderTos = new ArrayList<>();
        List<SkuMemberPriceTo> skuMemberPriceTos = new ArrayList<>();
        for (Map.Entry<Long, Skus> entry : entries) {
            Long id = entry.getKey();
            SkureductionTo skureductionTo = new SkureductionTo();
            skureductionTo.setFullPrice(entry.getValue().getFullPrice());
            skureductionTo.setReducePrice(entry.getValue().getReducePrice());
            skureductionTo.setSkuId(id);
            skureductionTos.add(skureductionTo);

            SkuLadderTo skuLadderTo = new SkuLadderTo();
            skuLadderTo.setSkuId(id);
            BeanUtils.copyProperties(entry.getValue(), skuLadderTo);
            // 计算价格
            skuLadderTo.setPrice(entry.getValue().getPrice().multiply(entry.getValue().getDiscount()));
            skuLadderTos.add(skuLadderTo);

            List<MemberPrice> memberPrice = entry.getValue().getMemberPrice();
            for (MemberPrice price : memberPrice) {
                if (price.getPrice().compareTo(new BigDecimal("0")) > 0) {
                    SkuMemberPriceTo skuMemberPriceTo = new SkuMemberPriceTo();
                    skuMemberPriceTo.setSkuId(id);
                    skuMemberPriceTo.setMemberPrice(price.getPrice());
                    skuMemberPriceTo.setMemberLevelId(price.getId());
                    skuMemberPriceTo.setMemberLevelName(price.getName());
                    skuMemberPriceTos.add(skuMemberPriceTo);
                }
            }
        }
        skuFullReductionFeignService.saveskureductionTos(skureductionTos);
        // 保存sms_sku_ladder打折表的信息
        skuLadderFeginService.saveSkuLadders(skuLadderTos);
        // 保存sms_member_price表的会员价信息
        memberPriceFeignService.saveMemberPrices(skuMemberPriceTos);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String catelogId = (String)params.get("catelogId");
        if (params.get("catelogId") != null && !"0".equals(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String)params.get("brandId");
        if (params.get("brandId") != null && !"0".equals(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String status = (String)params.get("status");
        if (params.get("status") != null) {
            queryWrapper.eq("publish_status", status);
        }
        String key = (String)params.get("key");
        if (StringUtils.hasText(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("id", key).or().like("spu_name", key);
            });
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

}